/*
 * Simple Editor to view contents
 *
 * Created on 1. August 2007, 13:49
 */
package com.google.cse.emea.universaltransformer.editors;

import com.google.cse.emea.jct.utils.Profile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;

/**
 * Simple stupid editor to show file contents
 * @author  jtrapp
 */
public class SimpleTextEditor extends javax.swing.JFrame implements EditorInterface {

    private static SimpleTextEditor simpleEditor = null;

    public static SimpleTextEditor getEditor() {
        if (simpleEditor == null) {
            simpleEditor = new SimpleTextEditor();
        }
        return simpleEditor;
    }

    /** Creates new form XMLEditor */
    public SimpleTextEditor() {
        initComponents();
    }

    public void setURL(String stringURL, Charset charset) throws IOException, BadLocationException {
        xmlEditorPane.setContentType("text");

        EditorKit kit = xmlEditorPane.getEditorKit();
        Document doc = xmlEditorPane.getDocument();
        doc.remove(0, doc.getLength());
        URL url = new URL(stringURL);
        InputStreamReader reader = new InputStreamReader(url.openStream(), charset);

        kit.read(reader, doc, 0);
    }

    /** Set the file to show.
     * @param filename File to show in editor
     * @param charset Character Set used while reading the file contents
     * @throws IOException Some IO Error
     * @throws BadLocationException Some Editor Error
     */
    public void setFile(String filename, String type, Charset charset)
            throws IOException, BadLocationException {
        setFile(new File(filename), type, charset);
    }

    /** Set the file to show.
     * @param file File to show in editor
     * @param charset Character Set used while reading the file contents
     * @throws IOException Some IO Error
     * @throws BadLocationException Some Editor Error
     */
    public void setFile(File file, String type, Charset charset) throws IOException, BadLocationException {
        xmlEditorPane.setContentType(type);
       
        EditorKit kit = xmlEditorPane.getEditorKit();
        Document doc = xmlEditorPane.getDocument();
        doc.remove(0, doc.getLength());
        InputStreamReader reader = new InputStreamReader(new FileInputStream(file), charset);

        kit.read(reader, doc, 0);
        statusLabel.setText("Size: " + file.length()+" \tLast modified: "+file.lastModified());
    }

    /** Show a zipped file.
     * @param zipfile Zip File from which to extract the file
     * @param entry Zip File entry name of the file to show
     * @param charset Character Set used while reading the file contents
     * @throws IOException Some IO Error
     * @throws BadLocationException Some Editor Error
     */
    public void setZippedFile(String zipfile, String entryName, String type, Charset charset) throws IOException, BadLocationException {
        xmlEditorPane.setContentType(type);
        EditorKit kit = xmlEditorPane.getEditorKit();
        Document doc = xmlEditorPane.getDocument();
        doc.remove(0, doc.getLength());
        try{
            ZipFile zFile = new ZipFile(zipfile);
            ZipEntry entry = zFile.getEntry(entryName);
            InputStream stream = zFile.getInputStream(entry);
            InputStreamReader reader = new InputStreamReader(stream, charset);
            kit.read(reader, doc, 0);
            statusLabel.setText("Size: " + entry.getCompressedSize()+"["+entry.getSize()+"] \tLast modified: "+entry.getTime());
        } catch (ZipException ze){
            setFile(zipfile, type, charset);
            statusLabel.setText("Warning: Unexpected File Format: Expected Zipped File.");
        }
        
    }


    public void viewFile(String filename, String zipEntry, String type,  String encoding) {
        
        setTitle(filename);
        File file = new File(filename);
        try {
            Charset charset = Charset.forName(encoding);
            if (zipEntry != null && zipEntry.length() > 0) {
                setZippedFile(file.getAbsolutePath(), zipEntry, type, charset);
            } else {
                setFile(file, type, charset);
            }
            setVisible(true);
        } catch (Exception ioe) {
            Logger.getLogger(getClass().getName()).log(Level.WARNING, "Can't open file window. " + ioe.getMessage(), ioe);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        xmlEditorPane = new javax.swing.JEditorPane();
        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        statusLabel = new javax.swing.JLabel();

        xmlEditorPane.setEditable(false);
        jScrollPane1.setViewportView(xmlEditorPane);

        jButton1.setText("close");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeEvent(evt);
            }
        });

        jScrollPane2.setViewportView(statusLabel);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane2)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void closeEvent(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeEvent
    this.setVisible(false);
}//GEN-LAST:event_closeEvent

    /**
     *  Standalone version of the simple editor.
     * For test only, becausethe editor is really stupid.
     * @param args the command line arguments
     */
    public static void main(final String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                SimpleTextEditor editor = new SimpleTextEditor();
                editor.setVisible(true);
                if (args.length > 0) {
                    try {
                        editor.setFile(args[0], "text", Charset.forName("UTF-8"));
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel statusLabel;
    private javax.swing.JEditorPane xmlEditorPane;
    // End of variables declaration//GEN-END:variables

    @Override
    public void viewFile(Profile profile, String prefix, String type) throws IOException {
        String filename = profile.get(prefix+"file");

        if ((filename!=null)&&(filename.length()>0)){
            String zipEntry =  profile.get(prefix+"zipEntry");
            String encoding = profile.get(prefix+"encoding");
            viewFile(filename, zipEntry, type,  encoding);
        } 
    }

     @Override
     public String[] getTypes() {
        return new String[] {"text/xml", "text/text", "text"};
    }
}
